package com.rd.p2p.app.user;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.PlatformInfo;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.common.util.IdCard;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;

import com.google.protobuf.TextFormat.ParseException;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.model.AppAuthenticationModel;
import com.qdlc.p2p.biz.service.DictService;
import com.qdlc.p2p.biz.service.user.UserEmailService;
import com.qdlc.p2p.biz.service.user.UserMobilePhoneService;
import com.qdlc.p2p.biz.service.user.UserRealNameService;
import com.qdlc.p2p.biz.util.ValidCodeSender;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.NoticeTplNid;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.dal.dto.Dict;
import com.qdlc.p2p.dal.dto.User;
import org.apache.struts2.convention.annotation.Result;

public class AppAuthenticationAction extends BaseAction<AppAuthenticationModel>
		implements ModelDriven<AppAuthenticationModel> {

	@Resource
	private DictService dictService;

	@Resource
	private UserMobilePhoneService userMobilePhoneService;

	@Resource
	private UserRealNameService userRealNameService;
	@Resource
	private UserEmailService userEmailService;

	@Resource
	private AdaptedRequestHandleService adaptedRequestHandleService;

	private Map<String, Object> data;

	/**
	 * 验证码
	 *
	 * @return
	 * @throws Exception
	 */
	@Action("/app/validimg")
	public String validimg() throws Exception {
		genernateCaptchaImage();
		return null;
	}

	/**
	 * 新浪实名
	 * 
	 * @throws Exception
	 */
	@Action(value = "/app/user/realName", results = {@Result(name = "realName", type = "ftl", location = "/mobile/member/useridentify/adapterRealName.html"),
			                                         @Result(name = "result", type = "ftl", location = "/mobile/result.html")})
	public String realName() throws Exception {
		User user = getSessionUser();
		if (user == null) {
			request.setAttribute("msg","用户尚未登录");
			return "result";
		}
		// 获取请求参数
		String cardId = paramString("cardId");
		String realName = paramString("realName");
		String msg = this.realNameMsg(cardId,realName,user,false);
		if(msg!=null){
			request.setAttribute("msg",msg);
			return "result";
		}else {
			return "realName";
		}
	}

	@Action("/app/user/appRealName")
	public void appRealName() throws Exception {
		User user = getSessionUser();
		data = new HashMap<String,Object>();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return ;
		}
		// 获取请求参数
		String cardId = paramString("cardId");
		String realName = paramString("realName");
		String msg = this.realNameMsg(cardId,realName,user,true);
		if(msg!=null){
			printWebResCodeAndMsgResult("0",msg);
			return;
		}else {
			data.put("html","/mobile/member/app/useridentify/adapterRealName.html");
			data.put("resCode","1");
			data.put("resMsg","实名认证页面跳转中");
			printWebJson(getStringOfJpaObj(data));
			return ;
		}
	}

	/**
	 * 绑定邮箱获取验证码
	 *
	 * @throws IOException
	 * @throws ParseException
	 */
	@Action("/app/user/bindEmailCode")
	public void bindEmailCode() throws Exception {
		User user = getSessionUser();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}
		ReturnResult result = ValidCodeSender.newInstance().sendCodeByEmail(user, model.getEmail(),
				NoticeTplNid.NOTICE_BIND_EMAIL);
		printWebResult(result.getErrorInfo(), result.isSuccess());
	}

	/**
	 * 添加邮箱认证信息
	 * 
	 * @throws IOException
	 * @throws ParseException
	 */
	@Action(value = "/app/user/email")
	public void email() throws IOException {
		User user = getSessionUser();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}
        //获取请求参数
		String code = paramString("code");
		String email = paramString("email");
		//修改邮箱,如果成功则修改User和UserIdentity信息

		ReturnResult result = userEmailService.modifyEmail(user, code, email);
		printWebResult(result.getErrorInfo(), result.isSuccess());
		printWebSuccess();
	}

	/**
	 * 绑定手机
	 * 
	 * @return
	 */
	@Action("/app/user/doBindPhone")
	public void doBindPhone() throws Exception {
		data = new HashMap<String, Object>();
		User user = getSessionUser();
		String code = paramString("code");
		String mobilePhone = paramString("mobilePhone");
		ReturnResult result = userMobilePhoneService.bindMobilePhone(user, code, mobilePhone);
		String resCode = result.isSuccess()? "1":"0";

		printWebResCodeAndMsgResult(resCode,result.getErrorInfo());
	}

	/**
	 * 取银行列表
	 * 
	 * @return
	 * @throws IOException
	 */
	@Action(value = "/app/user/accountBank")
	public void accountBank() throws IOException {
		User user = this.getSessionUser();
		if (user == null) {
			printWebResCodeAndMsgResult("-1","用户尚未登录!");
			return;
		}
		List<Dict> dictList = dictService.list("account_bank");
		data = new HashMap<String, Object>();
		data.put("resCode", "1");
		data.put("resMsg", "获取银行列表成功");
		data.put("data", dictList);
		printWebJson(getStringOfJpaObj(data));
	}

	private String checkParams(String cardId, String realName) {
		if (StringUtils.isBlank(cardId)) {
			return "身份证不能为空！";
		}
		if (StringUtils.isBlank(realName)) {
			return "姓名不能为空！";
		}
		// 验证身份证
		IdCard idCard = null;
		try {
			idCard = IdCard.getInstance(cardId);
		} catch (Exception e) {
			return "身份证无效!";
		}
		if ((idCard != null) && (idCard.getIdType() == IdCard.ID_NUM_V1)) {
			return "不支持一代身份证!";
		}
		if ((idCard != null) && (DateUtil.getLifeFullYear(idCard.getBirthday()) < 18)) {
			return "未满18周岁不能开户!";
		}
		return null;
	}

	private String realNameMsg(String cardId,String realName,User user,Boolean isSessionRequ){
		String returnUrl = SystemConfigHelper.getValue(SystemConfigHelper.Nid.WEB_URL) + "/tpp/tppAction/realNameCallBack.html";
		String pageUrl = SystemConfigHelper.getValue(SystemConfigHelper.Nid.WECHAT_URL) + "/mobile/usercenter/security/setting.html";
		realName = StringUtils.isBlank(realName) ? user.getRealName() : realName;
		cardId = StringUtils.isBlank(cardId) ? user.getCardId() : cardId;
		String msg = checkParams(cardId, realName);
		if (msg != null) {
			return msg ;
		}
		// 进行实名认证
		User realUser = userRealNameService.realName(user.getUserId(),cardId, realName);
		if (realUser != null) {
			PlatformInfo platformInfo = adaptedRequestHandleService.getPlatformInfo();
			request.setAttribute("domain", platformInfo.getDomain());
			request.setAttribute("merchantId", platformInfo.getMerchantId());
			request.setAttribute("terminalId", platformInfo.getTerminalId());
			String xml = String.format(
					"<?xml version='1.0' encoding='UTF-8'?><custody_req>" + "<bf_account>%s</bf_account>"
							+ "<name>%s</name>" + "<id_card>%s</id_card>" + "<user_id>%s</user_id>"
							+ "<return_url>%s</return_url>" + "<page_url>%s</page_url>" + "</custody_req>",
					user.getMobilePhone(), realName, cardId, realUser.getTppUserCustId(), returnUrl, pageUrl);
			request.setAttribute("requestParams", xml);
			request.setAttribute("sign", adaptedRequestHandleService.aesEncryptKey16(xml));
			if(isSessionRequ){
				session.put("domain", platformInfo.getDomain());
				session.put("merchantId", platformInfo.getMerchantId());
				session.put("terminalId", platformInfo.getTerminalId());
				session.put("requestParams", xml);
				session.put("sign", adaptedRequestHandleService.aesEncryptKey16(xml));
			}
			return msg;
		}
		else{
			msg = "实名认证失败";
			return msg;
		}
	}
}
